package com.market.manage.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.market.manage.mapper.RoleMapper;
import com.market.manage.po.Role;
import com.market.manage.po.RoleExample;
import com.market.manage.service.RoleService;
import com.market.po.Result;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Override
    public Result getRole() {
        Result result = new Result();
        List<Role> roles = roleMapper.selRoles();
        result.setMessage(roles);
        return result;
    }

    @Override
    public Result selRoles(Long id, String job, Integer pageIndex, Integer pageSize) {
        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
        if (id != null && id != 0) {
            criteria.andIdEqualTo(id);
        }
        if (!StringUtils.isEmpty(job)) {
            criteria.andJobLike("%" + job + "%");
        }
        //设置分页条件
        PageHelper.startPage(pageIndex, pageSize);
        List<Role> roles = roleMapper.selectByExample(roleExample);
        PageInfo<Role> pageInfo = new PageInfo<>(roles);
        Result result = new Result();
        result.setMessage(roles);
        result.setTotal(pageInfo.getTotal());
        return result;
    }

    @Override
    public void edit(Role role) {
        if (role.getId() != null && role.getId() != 0) {
            //编辑
            RoleExample roleExample = new RoleExample();
            RoleExample.Criteria criteria = roleExample.createCriteria();
            criteria.andIdEqualTo(role.getId());
            roleMapper.updateByExample(role, roleExample);
        } else {
            //新增
            roleMapper.insert(role);
        }
    }

    @Override
    public void delete(Long id) {
        roleMapper.deleteByPrimaryKey(id);
    }
}
